//
// Created by bigknife on 14-9-10.
// Copyright (c) 2014 51fmzg. All rights reserved.
//


#import "LanceTableView.h"
#import "VMCMacros.h"
//正常状态
#define STATE_NORMAL 0
//取消状态
#define STATE_CANCEL (-1)
//开始下拉刷新
#define REFRESH_STATE_DD_START 1
//下拉到DDR_NORMAL 视图高度，状态变为用户确认
#define REFRESH_STATE_DD_CONFIRM 2
//执行刷新
#define REFRESH_STATE_DD_DO_REFRESH 3
//取消刷新
#define REFRESH_STATE_DD_CANCEL_REFRESH 4
//完成刷新
#define REFRESH_STATE_DD_COMPLETE_REFRESH 5
//开始上拉加载更多
#define MORE_STATE_PU_START 11
//确认加载更多
#define MORE_STATE_PU_CONFIRM 12
//执行加载更多
#define MORE_STATE_PU_DO_LOAD_MORE 13
//完成加载更多
#define MORE_STATE_PU_COMPLETE_LOAD_MORE 14

@interface LanceTableView () <UITableViewDelegate, UITableViewDataSource>
@property(weak, nonatomic) id <LanceTableViewDelegate> realDelegate;
@property(weak, nonatomic) id <LanceTableViewDataSource> realDataSource;
@property(nonatomic) UIEdgeInsets originalCotentInsets;
@property(nonatomic) BOOL originalContentInsetsHasSet;
@property(nonatomic) NSInteger currentState;
@property(nonatomic) BOOL isLoading;
@property(nonatomic,strong) UIView *emptyView;
@property(nonatomic)NSInteger count;
@end

@implementation LanceTableView {

}
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
	self = [super initWithFrame:frame style:style];
	if (self) {
		[self innerInit];
	}
	return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
	self = [super initWithCoder:aDecoder];
	if (self) {
		[self innerInit];
	}
	return self;
}
-(void) innerInit{
	self.currentState = STATE_NORMAL;
	self.pumDisabled = YES;
	self.ddrDisabled = YES;
}
- (void)setContentInset:(UIEdgeInsets)contentInset {
	[super setContentInset:contentInset];
	if (!self.originalContentInsetsHasSet) {
		self.originalCotentInsets = contentInset;
		self.originalContentInsetsHasSet = YES;
	}

}
/*
-(void)reloadData{
	dispatch_async(dispatch_get_main_queue(), ^{
		[super reloadData];
	});
	
}
*/
- (void)setPumNormalView:(UIView *)pumNormalView {
	_pumNormalView = pumNormalView;
	pumNormalView.hidden = YES;
	[self addSubview:pumNormalView];
}

- (void)setPumConfirmView:(UIView *)pumConfirmView {
	_pumConfirmView = pumConfirmView;
	pumConfirmView.hidden = YES;
	[self addSubview:pumConfirmView];
}

- (void)setPumLoadingView:(UIView *)pumLoadingView {
	_pumLoadingView = pumLoadingView;
	pumLoadingView.hidden = YES;
	[self addSubview:pumLoadingView];
}

- (void)setDdrNormalView:(UIView *)ddrNormalView {
	_ddrNormalView = ddrNormalView;
	ddrNormalView.hidden = YES;
	[self addSubview:ddrNormalView];
}

- (void)setDdrConfirmView:(UIView *)ddrConfirmView {
	_ddrConfirmView = ddrConfirmView;
	ddrConfirmView.hidden = YES;
	[self addSubview:ddrConfirmView];
}

- (void)startRefresh {
	
	if(self.isLoading){
		return ;
	}
	
	
	self.currentState = REFRESH_STATE_DD_DO_REFRESH;
}


- (void)completeLoading {
	self.isLoading = NO;
	self.currentState = REFRESH_STATE_DD_COMPLETE_REFRESH;
	
	__weak LanceTableView *wself = self;
	if (self.count == 0 ) {
		if (self.emptyView) {
			dispatch_async(dispatch_get_main_queue(), ^{
				[wself addSubview:wself.emptyView];
			});
			
		}
	}else{
		if (self.emptyView) {
			dispatch_async(dispatch_get_main_queue(), ^{
				[wself.emptyView removeFromSuperview];
			});
			
		}
	}
}

-(UIView *)emptyView{
	if (_emptyView) {
		return _emptyView;
	}
	if ([self.realDelegate respondsToSelector:@selector(emptyViewOfTableView:)]) {
		_emptyView =  [self.realDelegate emptyViewOfTableView:self];
	}
	return _emptyView;
}

- (void)setDdrLoadingView:(UIView *)ddrLoadingView {
	_ddrLoadingView = ddrLoadingView;
	ddrLoadingView.hidden = YES;
	[self addSubview:ddrLoadingView];
}


- (void)layoutSubviews {
	[super layoutSubviews];
	if (!self.ddrNormalView.hidden) {
		self.ddrNormalView.frame = CGRectMake(0, -CGRectGetHeight(self.ddrNormalView.frame),
				CGRectGetWidth(self.frame), CGRectGetHeight(self.ddrNormalView.frame));
	}
	if (!self.ddrConfirmView.hidden) {
		self.ddrConfirmView.frame = CGRectMake(0, -CGRectGetHeight(self.ddrConfirmView.frame),
				CGRectGetWidth(self.frame), CGRectGetHeight(self.ddrConfirmView.frame));
	}
	if (!self.ddrLoadingView.hidden) {
		self.ddrLoadingView.frame = CGRectMake(0, -CGRectGetHeight(self.ddrLoadingView.frame),
				CGRectGetWidth(self.frame), CGRectGetHeight(self.ddrLoadingView.frame));
	}

	CGFloat pumY = 0;
	if (self.contentSize.height <= (CGRectGetHeight(self.frame) - (self.originalCotentInsets.top + self.originalCotentInsets.bottom))) {
		pumY = CGRectGetHeight(self.frame) - (self.originalCotentInsets.top + self.originalCotentInsets.bottom);
	} else {
		pumY = self.contentSize.height;
	}
	if (!self.pumNormalView.hidden) {
		self.pumNormalView.frame = CGRectMake(0, pumY,
				CGRectGetWidth(self.frame), CGRectGetHeight(self.pumNormalView.frame));
		//DLog("self.pumNormalView.frame:%@", NSStringFromCGRect(self.pumNormalView.frame));
	}
	if (!self.pumConfirmView.hidden) {
		self.pumConfirmView.frame = CGRectMake(0, pumY,
				CGRectGetWidth(self.frame), CGRectGetHeight(self.pumConfirmView.frame));
		//DLog("self.pumConfirmView.frame:%@", NSStringFromCGRect(self.pumConfirmView.frame));
	}
	if (!self.pumLoadingView.hidden) {
		self.pumLoadingView.frame = CGRectMake(0, pumY,
				CGRectGetWidth(self.frame), CGRectGetHeight(self.pumLoadingView.frame));
		//DLog("self.pumLoadingView.frame:%@", NSStringFromCGRect(self.pumLoadingView.frame));
	}

}


- (void)setDelegate:(id <LanceTableViewDelegate>)delegate {
	[super setDelegate:self];
	_realDelegate = delegate;
}

- (void)setDataSource:(id <LanceTableViewDataSource>)dataSource {
	[super setDataSource:self];
	_realDataSource = dataSource;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	
	if(self.isLoading){
		return ;
	}
	CGPoint offset = scrollView.contentOffset;
	CGFloat deltaY = offset.y + self.originalCotentInsets.top;

	//DLog("deltaY = %.2f, contentSize.height = %.2f", deltaY,self.contentSize.height);
	if (self.isDragging) {

		//下拉刷新状态跃迁
		if (!self.ddrDisabled) {
			if (deltaY < 0 && deltaY > -(CGRectGetHeight(self.ddrNormalView.frame))) {
				self.currentState = REFRESH_STATE_DD_START;
				return;
			} else if (deltaY <= -(CGRectGetHeight(self.ddrNormalView.frame)) && self.currentState == REFRESH_STATE_DD_START) {
				self.currentState = REFRESH_STATE_DD_CONFIRM;
				return;
			}
		}
		
		
		//pu 的 deltaY
		if (!self.pumDisabled) {
			if (self.contentSize.height <= (CGRectGetHeight(self.frame) - (self.originalCotentInsets.top + self.originalCotentInsets.bottom))) {
				//cell未撑满
			} else {
				//cell已经撑满
				deltaY = deltaY + CGRectGetHeight(self.frame) - (self.originalCotentInsets.top + self.originalCotentInsets.bottom) - self.contentSize.height;
			}
			
			if (deltaY > 0 && deltaY < CGRectGetHeight(self.pumNormalView.frame)) {
				self.currentState = MORE_STATE_PU_START;
			}else if (deltaY >= CGRectGetHeight(self.pumNormalView.frame) && self.currentState == MORE_STATE_PU_START) {
				self.currentState = MORE_STATE_PU_CONFIRM;
			}
		}

	}else{
		if(self.currentState == MORE_STATE_PU_START){
			self.currentState = STATE_CANCEL;
		}
	}
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	if(!self.isLoading)
	{
		self.currentState = STATE_NORMAL;
	}

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
	if(self.isLoading){
		return ;
	}
	//在start状态就释放，则转为取消状态
	if (self.currentState == STATE_NORMAL ||
			self.currentState == REFRESH_STATE_DD_START ||
			self.currentState == MORE_STATE_PU_START) {
		self.currentState = STATE_CANCEL;
		return ;
	}

	if (self.currentState == REFRESH_STATE_DD_CONFIRM) {
		self.currentState = REFRESH_STATE_DD_DO_REFRESH;
		return;
	}else if (self.currentState == MORE_STATE_PU_CONFIRM) {
		self.currentState = MORE_STATE_PU_DO_LOAD_MORE;
		return;
	}
	DLog("nothing, currentState=%d",(int)self.currentState);
}

#pragma mark - TableViewDataSource
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.realDataSource respondsToSelector:@selector(tableView:commitEditingStyle:forRowAtIndexPath:)]) {
		[self.realDataSource tableView:tableView commitEditingStyle:editingStyle forRowAtIndexPath:indexPath];
	}
}



#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.realDelegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
		[self.realDelegate tableView:tableView didSelectRowAtIndexPath:indexPath];
	}

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.realDelegate respondsToSelector:@selector(tableView:cellForRowAtIndexPath:)]) {
		return [(id) (self.realDelegate) tableView:tableView cellForRowAtIndexPath:indexPath];
	}
	return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if ([self.realDelegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {
		return [self.realDelegate tableView:tableView heightForRowAtIndexPath:indexPath];
	}
	return 44;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	if ([self.realDelegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
		return [self.realDelegate tableView:tableView viewForHeaderInSection:section];
	}
	return nil;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	if ([self.realDelegate respondsToSelector:@selector(tableView:heightForHeaderInSection:)]) {
		return [self.realDelegate tableView:tableView heightForHeaderInSection:section];
	}
	return 0;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger count = 0;
	if ([self.realDataSource respondsToSelector:@selector(tableView:numberOfRowsInSection:)]) {
		count = [self.realDataSource tableView:tableView numberOfRowsInSection:section];
	}
	self.count = count;
	return count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
	if ([self.realDataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
		return [self.realDataSource numberOfSectionsInTableView:tableView];
	}
	return 1;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
	if ([self.realDataSource respondsToSelector:@selector(sectionIndexTitlesForTableView:)]) {
		return 	[self.realDataSource sectionIndexTitlesForTableView:tableView];
	}
	return nil;
}

#pragma mark - 状态机
- (void)setCurrentState:(NSInteger)currentState {
	if(_currentState == currentState){
		return;
	}
	_currentState = currentState;
	switch (_currentState) {
		case STATE_NORMAL:
			[self fsmStateRunWhenNormal];
			break;
		case STATE_CANCEL:
			[self fsmStateRunWhenCancel];
			break;
		case REFRESH_STATE_DD_START:
			[self fsmRunWhenDD_Start];
			break;
		case REFRESH_STATE_DD_CONFIRM:
			[self fsmRunWhenDD_Confirm];
			break;
		case REFRESH_STATE_DD_DO_REFRESH:
			[self fsmRunWhenDD_DoRefresh];
			break;
		case REFRESH_STATE_DD_COMPLETE_REFRESH:
			[self fsmRunWhenDD_CompleteRefresh];
			break;

		case MORE_STATE_PU_START:
			[self fsmRunWhenPU_Start];
			break;
		case MORE_STATE_PU_CONFIRM:
			[self fsmRunWhenPU_Confirm];
			break;
		case MORE_STATE_PU_DO_LOAD_MORE:
			[self fsmRunWhenPU_DoLoadMore];
			break;
		case MORE_STATE_PU_COMPLETE_LOAD_MORE:
			[self fsmRunWhenPU_CompleteLoadMore];
			break;
		default:
			break;
	}
}

- (void)fsmRunWhenPU_CompleteLoadMore {
	//DLog("完成加载更多");
	[self setCurrentState:STATE_NORMAL];
	__weak LanceTableView *wself = self;
	[UIView animateWithDuration:0.3 animations:^{
		wself.contentInset = wself.originalCotentInsets;
	}];

}

- (void)fsmRunWhenPU_DoLoadMore {
	//DLog("执行加载更多");
	if (self.emptyView) {
		[self.emptyView removeFromSuperview];
	}
	self.isLoading = YES;

	self.pumLoadingView.hidden = NO;
	self.pumConfirmView.hidden = YES;
	self.pumNormalView.hidden = YES;

	__weak LanceTableView *wself = self;
	[UIView animateWithDuration:0.3 animations:^{
		UIEdgeInsets contentInset = wself.originalCotentInsets;
		contentInset.bottom += CGRectGetHeight(wself.pumLoadingView.frame);
		wself.contentInset = contentInset;
	}];

	id <LanceTableViewDelegate> o = self.realDelegate;
	if ([o respondsToSelector:@selector(LloadMoreForTableView:)]) {
		[o LloadMoreForTableView:self];
	}
}

- (void)fsmRunWhenPU_Confirm {
	//DLog("确认加载更多");
	self.pumConfirmView.hidden = NO;
	self.pumNormalView.hidden = YES;
	self.pumLoadingView.hidden = YES;
}

- (void)fsmRunWhenPU_Start {
	//DLog("开始加载更多");
	self.pumNormalView.hidden = NO;
	self.pumConfirmView.hidden = YES;
	self.pumLoadingView.hidden = YES;
}

- (void)fsmRunWhenDD_CompleteRefresh
{
	//DLog("完成下拉刷新");
	//直接回到正常状态
	[self setCurrentState:STATE_NORMAL];
	__weak LanceTableView *wself = self;
	[UIView animateWithDuration:0.3 animations:^{
		wself.contentInset = wself.originalCotentInsets;
	}];

}

- (void)fsmRunWhenDD_DoRefresh {
	//DLog("执行下拉刷新");
	if (self.emptyView) {
		[self.emptyView removeFromSuperview];
	}
	
	self.isLoading = YES;
	self.ddrLoadingView.hidden = NO;
	self.ddrNormalView.hidden = YES;
	self.ddrConfirmView.hidden = YES;

	__weak LanceTableView *wself = self;
	[UIView animateWithDuration:0.3 animations:^{
		UIEdgeInsets contentInset = wself.originalCotentInsets;
		contentInset.top += CGRectGetHeight(wself.ddrLoadingView.frame);
		wself.contentInset = contentInset;

	}];

	

	id <LanceTableViewDelegate> o = self.realDelegate;
	if ([o respondsToSelector:@selector(LrefreshForTableView:)]) {
		[o LrefreshForTableView:self];
	}
}

- (void)fsmRunWhenDD_Confirm{
	//DLog("确认下拉刷新");
	self.ddrConfirmView.hidden = NO;
	self.ddrNormalView.hidden = YES;
	self.ddrLoadingView.hidden = YES;
}

- (void)fsmRunWhenDD_Start {
	//DLog("准备下拉刷新");
	self.ddrNormalView.hidden = NO;
	self.ddrConfirmView.hidden = YES;
	self.ddrLoadingView.hidden = YES;
}

- (void)fsmStateRunWhenNormal {
	//DLog("正常状态");
	self.ddrNormalView.hidden = YES;
	self.ddrConfirmView.hidden = YES;
	self.ddrLoadingView.hidden = YES;
	self.pumNormalView.hidden = YES;
	self.pumConfirmView.hidden = YES;
	self.pumLoadingView.hidden = YES;
}
- (void)fsmStateRunWhenCancel {
	//DLog("取消状态");
	self.ddrNormalView.hidden = YES;
	self.ddrConfirmView.hidden = YES;
	self.ddrLoadingView.hidden = YES;
	self.pumNormalView.hidden = YES;
	self.pumConfirmView.hidden = YES;
	self.pumLoadingView.hidden = YES;
}
-(void)setPumDisabled:(BOOL)pumDisabled{
	_pumDisabled = pumDisabled;
	if (_pumDisabled)
	{
		self.pumNormalView.hidden = YES;
		self.pumLoadingView.hidden = YES;
		self.pumLoadingView.hidden = YES;
	}
}
-(void)setDdrDisabled:(BOOL)ddrDisabled{
	_ddrDisabled = ddrDisabled;
	if (_ddrDisabled) {
		self.ddrNormalView.hidden = YES;
		self.ddrConfirmView.hidden = YES;
		self.ddrLoadingView.hidden = YES;
	}
}
@end